const {
  GiftShopModel
} = require('../../../utils/giftshop-model.js');
var giftShopModel = new GiftShopModel();
Page({

  /**
   * 页面的初始数据
   * 
   */
  data: {
    isAddressShow: null,
    isPassword: false, //支付密码弹出层
    currency: [],
    goodsList: [], //商品列表
    memberAddress: null, //地址信息
    totalPrice: [], //总价格
    paymentType: null, //1.从购物车过来
    remark: '', //备注
    payType: '', //支付状态 0
    orderCode: '', //订单编号
    orderPayInfo: {}, //密码信息
    disabled: true,
    shopId: '',
    from: '',
    numDisabled: false, //输入框是否可以点击
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.setData({
      currency: JSON.parse(options.currency) || [],
      paymentType: options.paymentType || null,
      from: options.from || ''
    }, function () {
      that.setBalanceInfo();
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.orderCode) {
      this.closePay();
    }
  },

  /**
   * 备注
   */
  setRemark: function (e) {
    var name = /[^A-Za-z0-9\u4e00-\u9fa5]/g;
    var value = e.detail.value;
    if (name.test(value)) {
      this.setData({
        remark: this.data.remark
      })
    } else {
      this.setData({
        remark: value
      })
    }
  },

  /**
   * 关闭支付密码
   */
  closeDialog: function () {
    this.setData({
      isPassword: false
    })
  },

  /**
   * 提交订单
   */
  createOrder: function () {
    wx.reportAnalytics('order_payment');
    let that = this;
    that.setData({
      disabled: true
    })
    let balanceSku = that.data.goodsList.map(item => {
      return {
        skuId: item.skuId,
        quantity: item.quantity,
        selectedPriceType: item.goodsPrice.priceType
      }
    })
    const shopInfo = wx.getStorageSync('shopInfo')
    var param = {
      merchantId: wx.getStorageSync('merchantId'), //商户ID
      shopId: shopInfo.shopId, //门店id
      addressId: that.data.memberAddress ? that.data.memberAddress.memberAddressId : '', //地址ID
      remark: that.data.remark //用户备注
    }
    if (that.data.paymentType == 1) {
      param.balanceCartDetailList = that.data.currency //购物车明细id
    } else if (that.data.paymentType == 2) {
      param.balanceSku = balanceSku //结算的SKU
    }
    giftShopModel.balanceCreateOrder(param).then(data => {
      that.setData({
        orderCode: data.orderCode,
        isPassword: true,
        shopId: shopInfo.shopId
      })
    }).catch(err => {
      that.setData({
        disabled: false
      })
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 关闭支付页面
   */
  closePay: function (e) {
    wx.reportAnalytics('order_payment_close');
    const shopInfo = wx.getStorageSync('shopInfo')
    wx.redirectTo({
      url: '/pages/giftShop/payment/waitingPayment/index?orderCode=' + this.data.orderCode + '&shopId=' + shopInfo.shopId
    })
  },

  /**
   * 
   * 支付成功
   */
  orderPaymentSuccess: function () {
    wx.reportAnalytics('order_payment_success');
    const shopInfo = wx.getStorageSync('shopInfo')
    wx.redirectTo({
      url: '/pages/giftShop/payment/paymentSuccess/index?shopId=' + shopInfo.shopId + '&orderCode=' + this.data.orderCode
    })
  },

  /**
   * 选地址
   */
  goAddressList: function () {
    wx.reportAnalytics('order_select_address');
    let memberAddressId = this.data.memberAddress ? this.data.memberAddress.memberAddressId : '' //地址ID
    wx.navigateTo({
      url: '/pages/giftShop/address/addressList/index?type=1&memberAddressId=' + memberAddressId
    })
  },

  /**
   * 减商品数量
   */
  decrease: function (e) {
    wx.reportAnalytics('order_quantity_decrease');
    if (!this.data.numDisabled) {
      let detail = e.currentTarget.dataset.detail //当前索引
      let quantity = parseInt(detail.quantity); //单个商品数量
      if (quantity > 1) {
        const goodsItem = (this.data.currency || []).map(item => {
          return {
            ...item,
            quantity: quantity - 1,
          }
        });
        this.setData({
          currency: goodsItem
        })
        this.setBalanceInfo()
      }
    }
  },

  /**
   * 加商品数量
   */
  increase: function (e) {
    wx.reportAnalytics('order_quantity_increase');
    let that = this;
    const goodsData = that.data.currency || []
    let detail = e.currentTarget.dataset.detail //当前索引
    if (detail.quantity < 99) {
      if (!that.data.numDisabled) {
        let quantity = parseInt(detail.quantity) + 1; //单个商品数量
        const goodsItem = (that.data.currency || []).map(item => {
          return {
            ...item,
            quantity: quantity,
          }
        });
        that.setData({
          currency: goodsItem
        }, () => {
          that.setBalanceInfo(goodsData)
        })
      }
    } else {
      wx.showToast({
        title: `购买上限99`,
        icon: 'none',
        duration: 2000
      })
    }
  },

  /**
   * 输入框编辑商品数量
   */
  editNum: function (e) {
    let that = this;
    const goodsData = that.data.currency || []
    if (e.detail.value > 99) {
      let detail = e.currentTarget.dataset.detail //当前索引
      let quantity = parseInt(detail.quantity); //单个商品数量
      const goodsItem = (that.data.currency || []).map(item => {
        return {
          ...item,
          quantity: quantity,
        }
      });
      that.setData({
        currency: goodsItem
      }, () => {
        wx.showToast({
          title: `购买上限99`,
          icon: 'none',
          duration: 2000
        })
        setTimeout(function () {
          that.setBalanceInfo()
        }, 1500)
      })
    } else {
      let quantity = parseInt(e.detail.value); //单个商品数量
      const goodsItem = (that.data.currency || []).map(item => {
        return {
          ...item,
          quantity: quantity,
        }
      });
      that.setData({
        currency: goodsItem
      }, () => {
        that.setBalanceInfo(goodsData)
      })
    }
  },

  /**
   * 去结算
   */
  setBalanceInfo: function (goodsData) {
    const shopInfo = wx.getStorageSync('shopInfo')
    let that = this;
    that.setData({
      numDisabled: true
    }, () => {
      var param = {
        merchantId: wx.getStorageSync('merchantId'), //商户ID2
        shopId: shopInfo.shopId, //门店id
        addressId: that.data.memberAddress ? that.data.memberAddress.memberAddressId : '', //地址ID
      }
      if (that.data.paymentType == 1) {
        param.balanceCartDetailList = that.data.currency //购物车明细id
      } else if (that.data.paymentType == 2) {
        param.balanceSku = that.data.currency //结算的SKU
      }
      giftShopModel.balanceInfo(param).then(data => {
        that.setData({
          goodsList: data.goodsList || [], //商品列表
          memberAddress: data.memberAddress || null, //地址信息
          totalPrice: data.total.totalPrice || [], //总价格
          isAddressShow: data.memberAddress ? true : false,
          disabled: data.memberAddress ? false : true,
          numDisabled: false
        })
        if (this.data.from === 'shoppingcart') {
          const pages = getCurrentPages()
          const prevPage = pages[pages.length - 2]
          prevPage.setData({
            memberAddressId: (data.memberAddress || {}).memberAddressId
          })
        }
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
        that.setData({
          numDisabled: false,
          disabled: true,
        })
        setTimeout(function () {
          if (goodsData && that.data.paymentType == 2 && err.error.indexOf("库存不足") > -1) {
            that.setData({
              currency: goodsData
            }, function () {
              that.setBalanceInfo()
            })
          }
        }, 1500)
      })
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.closeDialog();
  },
})